#include "hal_audio.h"
#include "hk32c030xx_gpio.h"
#include "systick.h"
#include "FreeRTOS.h"

#define DATA_SET_HIGHT      GPIO_SetBits(AUDIO_DATA_BASE,AUDIO_DATA_PIN)
#define DATA_SET_LOW        GPIO_ResetBits(AUDIO_DATA_BASE,AUDIO_DATA_PIN)

//#define CLK_SET_HIGHT      GPIO_SetBits(AUDIO_CLK_BASE,AUDIO_CLK_PIN)
//#define CLK_SET_LOW        GPIO_ResetBits(AUDIO_CLK_BASE,AUDIO_CLK_PIN)

//#define BUSY_SET_HIGHT      GPIO_ResetBits(AUDIO_BUSY_BASE,AUDIO_BUSY_PIN)
//#define BUSY_SET_LOW        GPIO_SetBits(AUDIO_BUSY_BASE,AUDIO_BUSY_PIN)

static void wt588_init() {
	
	GPIO_InitTypeDef audio;
	RCC_AHBPeriphClockCmd(AUDIO_BUSY_CORE, ENABLE);
	
    audio.GPIO_Pin = AUDIO_DATA_PIN;
    audio.GPIO_Mode = GPIO_Mode_OUT;
    audio.GPIO_OType = GPIO_OType_PP;
    audio.GPIO_Speed = GPIO_Speed_50MHz;
    audio.GPIO_PuPd = GPIO_PuPd_NOPULL;
    audio.GPIO_Schmit = GPIO_Schmit_Disable;
    GPIO_Init(AUDIO_DATA_BASE, &audio);
}

static void wt588_play(uint8_t id) {
#if 0
//	CLK_SET_HIGHT;
//	DATA_SET_HIGHT;
//	uint8_t s_data = id;
//	CLK_SET_LOW;
//	delay_ms(5);
//	
//	int flage = s_data & 0x01;
//    for(int i = 0; i < 8;i++) {
//		CLK_SET_LOW;
//        if(flage) {
//            DATA_SET_HIGHT;
//        } else {
//            DATA_SET_LOW;
//        }
//		delay_us(300);
//		CLK_SET_HIGHT;
//		delay_us(300);
//		s_data = s_data >> 1;
//		flage = s_data & 0x01;
//    }
//    DATA_SET_HIGHT;
//	CLK_SET_HIGHT;

#else 
	uint8_t s_data = id;

	DATA_SET_LOW;
	vTaskDelay(5);
	int flage = s_data & 0x01;
	for(int i = 0; i < 8;i++) {
		if(flage) {
			DATA_SET_HIGHT;
			vTaskDelay(3);
			DATA_SET_LOW;
			vTaskDelay(1);
		} else {
			DATA_SET_HIGHT;
			vTaskDelay(1);
			DATA_SET_LOW;
			vTaskDelay(3);
		}
		
		s_data = s_data >> 1;
		flage = s_data & 0x01;
	}
	DATA_SET_HIGHT;
#endif
} 

static void wt588_play_couple(uint8_t id_1,uint8_t id_2) {
    
    wt588_play(0xf3);
    delay_ms(2);
    wt588_play(id_1);
    delay_ms(5);
    wt588_play(0xf3);
    delay_ms(2);
    wt588_play(id_2);
    delay_ms(5);
}

const audio_t_ g_audio_ = {
    wt588_init,
    wt588_play,
    wt588_play_couple
};

